package com.leyou.item.web;

import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 根据id查询分类
     * @param id 分类id
     * @return 分类对象
     */
    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> findCategoryById(@PathVariable("id") Long id) {
        //根据id查询
        Category category = categoryService.getById(id);
        //转DTO
        CategoryDTO categoryDTO = new CategoryDTO(category);
        //封装结果，返回200
        return ResponseEntity.ok(categoryDTO);
    }

    /**
     *  根据id集合查询分类集合
     * @param ids
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long> ids) {
        //根据ids查询
        List<Category> categoryList = categoryService.listByIds(ids);
        List<CategoryDTO> dtoList = new ArrayList<>(categoryList.size());
        for (Category category : categoryList) {
            dtoList.add(new CategoryDTO(category));
        }
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据父类目id，查询子类目的集合
     * @param parentId
     * @return
     */
    @GetMapping("/of/parent")
    //select* from tb_category where parent_id =0
    public ResponseEntity<List<CategoryDTO>> queryCategoryByParentId(@RequestParam("pid") Long parentId) {
        List<Category> list = categoryService.query().eq("parent_id", parentId).list();
        //转dto
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(list);
        //封装结果，返回200
        return ResponseEntity.ok(dtoList);
    }


    /**
     * 根据品牌id，查询商品分类的集合
     * @param brandId
     * @return
     */
    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByBrandId(@RequestParam("id") Long brandId) {
        List<CategoryDTO> doList = categoryService.queryCategoryByBrandId(brandId);
        return ResponseEntity.ok(doList);
    }
}
